//
// Created by 24087 on 2025/3/5.
//

#include "../Inc/Key.h"
uint8_t volatile _Key_value = 0;
uint8_t _count = 0;
uint8_t _lastCheck = 0, _currentCheck = 0;

/*每隔20ms进行一次按键检测*/
void Key_Tick()
{
    _count++;
    if (_count >= 20)
    {
        /*清空标志位*/
        _count = 0;

        /*检测标志位修正*/
        _lastCheck = _currentCheck;
        _currentCheck = Key_GetState();

        /*判断按键状态*/
        if (_currentCheck == 0 && _lastCheck != 0)
        {
            _Key_value = _lastCheck;
        }
    }
}

/*返回按键的值，用来确定是哪个按键被按下*/
uint8_t Key_GetState()
{
    if (HAL_GPIO_ReadPin(Key1_GPIO_Port, Key1_Pin) == GPIO_PIN_RESET) return 1;
    if (HAL_GPIO_ReadPin(Key2_GPIO_Port, Key2_Pin) == GPIO_PIN_RESET) return 2;
    if (HAL_GPIO_ReadPin(Key3_GPIO_Port, Key3_Pin) == GPIO_PIN_RESET) return 3;
    if (HAL_GPIO_ReadPin(Key4_GPIO_Port, Key4_Pin) == GPIO_PIN_RESET) return 4;

    return 0;
}

/*用来返回按键的有效值，并复位操作，否则会导致按键被判断为一直按下*/
uint8_t Key_GetValue()
{
    const uint8_t temp = _Key_value;
    _Key_value = 0;
    return temp;
}
